package com.store.orm.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.LinkedHashMap;

/**
 * JSON 工具类，主要是为了解析 JSON 字符串为实体类或LinkedHashMap
 * 将实体类解析为 JSON 字符串
 *
 * @author 宫静雨
 * @version 1.0
 */
public final class JsonUtil {
    private static final ObjectMapper om = new ObjectMapper();

    public static LinkedHashMap<String, Object> parse(String json) {
        try {
            return om.readValue(json, new TypeReference<LinkedHashMap<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T toBean(String json, Class<T> cls) {
        try {
            return om.readValue(json, cls);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> String toJson(T t) {
        try {
            return om.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
